<template>
    <el-form
      :label-position="labelPosition"
      label-width="auto"
      :model="form"
      style="max-width: 600px"
    >
      <el-form-item label="姓名" :label-position="itemLabelPosition">
        <el-input v-model="form.username" />
      </el-form-item>
      <el-form-item label="性别" :label-position="itemLabelPosition">
        <el-select v-model="form.sex" placeholder="请选择">
            <el-option label="男" value="男" />
            <el-option label="女" value="女" />
          </el-select>
      </el-form-item>
      <el-form-item label="年龄" :label-position="itemLabelPosition">
        <el-input-number v-model="form.age" />
      </el-form-item>
    </el-form>
    <el-button type="primary" @click="saveOrUpdate">
        {{ title }}
    </el-button>
  </template>
  
  <script lang="ts" setup>
  import { reactive, ref } from 'vue'
  import type { FormItemProps, FormProps } from 'element-plus'
  import axios from 'axios';
  import {useRouter} from 'vue-router'
import { onMounted } from 'vue';
  
  const labelPosition = ref<FormProps['labelPosition']>('right')
  const itemLabelPosition = ref<FormItemProps['labelPosition']>('')

  let form = reactive({
    id:null,
    username:'',
    sex:'男',
    age:1
  })

  const title = ref('添加')

  const router = useRouter()

  //接收数据
  onMounted(()=>{
    let result = history.state.params
    if(result){
       title.value = '修改'
       form={...result}
        const person = JSON.parse(result)
        //Object.assign(form,person)
        form={...person}
    }
  })


  const saveOrUpdate=()=>{
    if(form.id){
      update()
    }else{
        save()
    }    
  }
  const save=()=>{
    axios({
        method:'post',
        url:'/api/person.do',
        data:{"method":"add",...form}  
          
    }).then(()=>{
        console.log('---------->>>');
       router.push({'path':'/person'})
    })
  }
  const update=()=>{
    axios({
        method:'post',
        url:'/api/person.do',
        data:{"method":"update",...form}  
          
    }).then(()=>{
       router.push({'path':'/person'})
    })
  }
  </script>